from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from application.models import Student
from application.serializer import StudentSerializer


class StudentsAPIView(APIView):
    """
    获取所有
    """
    def get(self, request):
        queryset = Student.objects.all()
        serializer=StudentSerializer(queryset, many=True)
        return Response(serializer.data)
    def post(self, request):
        serializer = StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class StudentDetailAPIView(APIView):
    def get(self, request,pk):
        try:
          queryset = Student.objects.get(pk=pk)
          serializer=StudentSerializer(queryset, many=False)
          return Response(serializer.data)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)
    def post(self, request):
        serializer = StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def put(self, request):
        serializer = StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def delete(self, request, pk):
        try:
            student = Student.objects.get(pk=pk)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)
        student.is_deleted = True
        student.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
